import 'package:flutter/material.dart';
import 'package:flutter_van_android/utils/router_manager.dart';

enum Status {
  LOADING, //加载中
  EMPTY, // 空视图
  FAILED, //加载失败
  LOADED //加载完成
}

class StatusView extends StatefulWidget {
  final Status status;
  final WidgetBuilder? builder;
  final VoidCallback? retry;
  final StatusViewController? statusViewController;

  StatusView({
    this.status = Status.LOADING,
    this.retry,
    this.builder,
    this.statusViewController,
  }) : super(key: statusViewController?._key);

  @override
  State<StatusView> createState() => _StatusViewState();
}

class _StatusViewState extends State<StatusView> {
  late Status _status;

  @override
  void initState() {
    super.initState();
    _status = widget.status;
  }

  @override
  Widget build(BuildContext context) {
    return switch (_status) {
      Status.LOADING => const SizedBox.shrink(),
      Status.EMPTY => const SizedBox.shrink(),
      Status.FAILED => const SizedBox.shrink(),
      Status.LOADED => widget.builder?.call(context) ?? const SizedBox.shrink(),
    };
  }

  void _changeStatus(Status status) {
    if (_status != status) {
      setState(() => _status = status);
    }
  }
}

Widget _baseView(List<Widget> items) {
  return CustomScrollView(
    physics:
        const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
    slivers: [
      SliverFillRemaining(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: items,
        ),
      )
    ],
  );
}

class StatusViewController {
  final GlobalKey<_StatusViewState> _key = GlobalKey();

  bool get isReady => _key.currentState != null && _key.currentState!.mounted;

  _StatusViewState? get _state => isReady ? _key.currentState : null;

  void showLoading() => _state?._changeStatus(Status.LOADING);

  void showEmpty() => _state?._changeStatus(Status.EMPTY);

  void showFiled() => _state?._changeStatus(Status.FAILED);

  void showLoaded() => _state?._changeStatus(Status.LOADED);
}
